//初始化楼栋树

//树形节点点击添加
var countTreeId;
$(function(){
    initBuildingTree();
});

//验证
$(document).ready(function () {
    $.formValidator.initConfig({
        formid: "frmMain", onerror: function (msg) {return false;}, onsuccess: function () {return true;}
    });
    $("#buildingType").formValidator({
        onfocus: "请选择建筑类型",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        onempty: "请选择建筑类型",
        onerror: "请选择建筑类型"
    });
    $("#num").formValidator({
        onfocus: "请输入排序编号",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        max: 10,
        onempty: "请输入排序编号",
        onerror: "请输入排序编号"
    }).RegexValidator({
        regexp: "intege1",
        datatype: "enum",
        onerror: "排序编号只能为正整数"
    });

    $("#buildingDesc").formValidator({
        onfocus: "请输入建筑名称",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        max: 20,
        onempty: "请输入名称描述",
        onerror: "不能为空，不得大于20个字符长度"
    });
});

//获取列表部门树数据
function initBuildingTree(){
    // PostForm("/cwp/front/sh/intebuilding!execute", "uid=building004", "", successResultBuilding, '',"frmTree");
    $.getJSON('/cwp/src/json/build.json',function(data){
        successResultBuilding(data);
    })
}

function successResultBuilding(result){
    switch (result.returnCode) {
        case "0":
            $("#dataTreeTotal").text( "共"+ result.beans.length +"条记录");
            if(result.beans.length>0)
                constructTree(result.beans);
            break;
        case "1":
            tipModal("icon-cross", "建筑树获取失败");
            break;
        case "-9999":
            tipModal("icon-cross", "建筑树获取失败");
            break;
    }
}

//建筑类型选择
$("#buildingType").on("change",function(){
    if($(this).val() == "0"){
        $("#parentText").val("");
        $("#parentId").val("");
        $(".pnode").hide();
    }
    else{
        $(".pnode").show();
    }
});

//1、判断建筑类型为区域
//2、根据父ID归类
//3、
//重构树对象数据
function constructTree(data){
    var zNodes=[];
    for(var i=0; i<data.length; i++){
        var obj = new Object();
        obj.id=data[i].buildingId;
        obj.pId=data[i].parentId;
        obj.name=data[i].buildingDesc;
        obj.num=data[i].num;
        switch (data[i].buildingType) {
            case "0":
                obj.buildingType="园区";
                break;
            case "1":
                obj.buildingType="楼栋";
                break;
            case "2":
                obj.buildingType="区域";
                break;
            case "3":
                obj.buildingType="楼层";
                break;
        }
        zNodes.push(obj);
    }

    var setting = {
        view: {
            showIcon: false,
            selectedMulti: false,
            addDiyDom:addDiyDom
        },
        data: {
            simpleData: {
                enable: true
            }
        },
    };
    $.fn.zTree.init($("#treeOrg"), setting, zNodes);
    var zTree = $.fn.zTree.getZTreeObj("treeOrg");
    if(countTreeId!=undefined && countTreeId!=""){
        var getTreeNode=zTree.getNodeByTId(countTreeId);
        //默认选中节点
        zTree.selectNode(getTreeNode);
        //默认展开节点
        zTree.expandNode(getTreeNode,true);
    }
    //添加表头
    var li_head=' <li class="head"><a><div class="diy">建筑名字</div><div class="diy">建筑类型</div><div class="diy">排序编号</div>' +
        '<div class="diy">操作</div></a></li>';
    var rows = $("#treeOrg").find('li');
    if(rows.length>0){
        rows.eq(0).before(li_head)
        $("#dataTreeData").remove();
    }else{
        $("#treeOrg").append(li_head);
        $("#treeOrg").append('<li><td style="text-align: center;line-height: 30px;" >无符合条件数据</li>')
    }
}



;

//新增保存
$("#btn_saveUser").on("click",function(){
    //判断表单验证是否通过
    if($.formValidator.PageIsValid()){
        var buildingId=$("#hidBuildingId").val();
        if(buildingId==""){
            PostForm("/cwp/front/sh/intebuilding!execute", "uid=i006", "post", successResultSaveBuilding, '',"frmMain");
        }
        else{
            PostForm("/cwp/front/sh/intebuilding!execute", "uid=building002", "post", successResultEditBuilding, '',"frmMain");
        }
    }
});

//新增请求成功回调函数
function successResultSaveBuilding(result) {
    switch (result.returnCode) {
        case "0":
            $("#modalDistrict").modal("hide");
            tipModal("icon-checkmark", "保存成功");
            initBuildingTree();
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "保存失败");
            break;
    }
}

//编辑建筑信息回调
function successResultEditBuilding(result){
    switch (result.returnCode) {
        case "0":
            $("#modalDistrict").modal("hide");
            tipModal("icon-checkmark", "保存成功");
            initBuildingTree();
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "保存失败");
            break;
    }
}
function beforeRemove(id) {
    $("#buildingId").val(id.getAttribute("data-id"));
    $("#modalDelBuilding").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
    return false;
}

//删除节点
$("#btnDelete").on("click",function(){
    PostForm("/cwp/front/sh/intebuilding!execute", "uid=building003", "", delBuildingbyId, "","frmTree");
});
function delBuildingbyId(result){
    $("#modalDelBuilding").modal("hide");
    switch (result.returnCode) {
        case "0":
            tipModal("icon-checkmark", "删除成功");
            initBuildingTree();
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "删除失败");
            break;
    }
}
//编辑
function beforeEditName(id) {
    addDeptTreeModal();
    // setTimeout(function() {
    //     $("#buildingId").val(id.getAttribute("data-id"));
    //     PostForm("/cwp/front/sh/intebuilding!execute", "uid=building001", "", getBuildingById, '',"frmTree");
    // }, 0);
    // return false;
}
//显示建筑详情
function getBuildingById(result){
    modalDistrict();
    $("#modalDistrict .modal-title").html("编辑建筑");
    switch (result.returnCode) {
        case "0":
            $("#parentId").val(result.object.parentId);
            $("#hidBuildingId").val(result.object.buildingId);
            $("#buildingType").val(result.object.buildingType);
            $("#num").val(result.object.num);
            $("#buildingDesc").val(result.object.buildingDesc);
            if(result.object.parentId != 0){
                $("#parentText").val(result.object.parentDesc);
            }else{
                $("#parentText").val("")
            }
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "获取详情失败");
            break;
    }
}


//打开模态框
function modalDistrict(){
    //$("#modalAddDistrict").html(modal);
    $(".tipArea div").html("").attr("class","");
    //$("#parentId").val("");
    $("#modalDistrict .modal-title").html("新增建筑");
    $("#hidBuildingId").val("");
    $("#parentText").val("")
    $("#buildingType").val("");
    $("#num").val("");
    $("#buildingDesc").val("");
    $("#modalDistrict").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
}

//点击节点事件
function beforeClick(treeId, treeNode){
    var buildingId=treeNode.id;
    $("#buildingId").val(buildingId);
    isFirst=true;
    //searchUserList(1);
}
//新增
$('#btnAddBuilding').on("click",function(){
    modalDistrict();
    addDeptTreeModal();
});


//自定义DOM节点
function addDiyDom(treeId, treeNode) {
    countTreeId = treeNode.tId;
    var spaceWidth = 15;
    var liObj = $("#" + treeNode.tId);
    var aObj = $("#" + treeNode.tId + "_a");
    var switchObj = $("#" + treeNode.tId + "_switch");
    var icoObj = $("#" + treeNode.tId + "_ico");
    var spanObj = $("#" + treeNode.tId + "_span");
    aObj.attr('title','');
    aObj.append('<div class="diy swich"></div>');
    var div = $(liObj).find('div').eq(0);
    switchObj.remove();
    spanObj.remove();
    icoObj.remove();
    div.append(switchObj);
    div.append(spanObj);
    $("#" + treeNode.tId + "_span").text(treeNode.buildingDesc);
    var spaceStr = "<span style='height:1px;display: inline-block;width:" + (spaceWidth * treeNode.level) + "px'></span>";
    switchObj.before(spaceStr);
    var editStr = '';
    editStr += '<div class="diy">' + (treeNode.buildingType )+ '</div>';
    editStr += '<div class="diy">' + (treeNode.num )+ '</div>';
    editStr += '<div class="diy"><a class="t-btn t-btn-sm t-btn-red t-btn-deal btnDelete tree-btnred" onclick="beforeRemove(this)" data-tid="'+ treeNode.tId +'"   data-id="'+ treeNode.id +'">删除</a><a class="t-btn t-btn-sm t-btn-blue t-btn-deal editDictData tree-btnblue" onclick="beforeEditName(this)"  data-tid="'+ treeNode.tId +'"   data-id="'+ treeNode.id +'" >编辑</a></div>';
    aObj.append(editStr);
    $("#" + treeNode.tId + "_a").on("click",function(){
        $("#parentId").val(treeNode.id);
    })
}
//新增初始化部门数
function addDeptTreeModal(){
        modalDistrict();
    // PostForm("/cwp/front/sh/intebuilding!execute", "uid=building004", "", getDeptTreeModal, '',"frmTree");

}
//获取数据初始化部门树
function getDeptTreeModal(result){
    var zNodes=[];
    for(var i=0; i<result.beans.length; i++){
        var obj = new Object();
        obj.id=result.beans[i].buildingId;
        obj.pId=result.beans[i].parentId;
        obj.name=result.beans[i].buildingDesc;
        zNodes.push(obj);
    }
    if(result.returnCode=="0"){
        //配置组织结构树
        var setting = {
            view: {
                dblClickExpand: false,
                showIcon: false,                 //隐藏节点图标
                selectedMulti: false             //设置是否允许同时选中多个节点
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeClick: beforeClickSelect
            }
        };

        $.fn.zTree.init($("#treeOrgModal"), setting, zNodes);
        var zTree = $.fn.zTree.getZTreeObj("treeOrgModal");
        if(countTreeId!=undefined && countTreeId!=""){
            var getTreeNode=zTree.getNodeByTId(countTreeId);
            //默认选中节点
            zTree.selectNode(getTreeNode);
            //默认展开节点
            zTree.expandNode(getTreeNode,true);
        }
    }
}
//渲染新增部门树
function beforeClickSelect(treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("treeOrgModal");
    $("#parentText").val(treeNode.name);
    $("#parentText").blur();
    $("#parentId").val(treeNode.id);
    hideMenu();
    return false;
}

$("#parentText").on("focus",function(){
    showMenu();
});
//显示部门树
function showMenu() {
    var deptIdObj = $("#parentText");
    var deptIdOffset = $("#parentText").offset();
    //$("#menuContent").slideDown("fast");
    $("#menuContent").css({left:deptIdOffset.left + "px", top:deptIdOffset.top + deptIdObj.outerHeight() + "px"}).slideDown("fast");
    $("body").bind("mousedown", onBodyDown);
}
//隐藏部门树
function hideMenu() {
    $("#menuContent").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
    if (!(event.target.id == "parentText" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
        hideMenu();
    }
}
